package com.example.demo.config.globalexception;

import com.example.demo.config.response.ErrorInfo;
import com.example.demo.config.response.ResponseResult;
import com.example.demo.config.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @author
 * 全局异常处理
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 系统异常
     *
     * @param req  请求信息
     * @param exception 异常信息
     * @return  异常封装
     */
    @ExceptionHandler(value = SystemRuntimeException.class)
    @ResponseBody
    public ErrorInfo bizExceptionHandler(HttpServletRequest req, SystemRuntimeException exception){
        log.error("SystemRuntimeException:", exception);

        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setCode(ResultCode.FAILURE.getCode());
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setUrl(req.getRequestURI());

        log.error("errorInfo:{}", errorInfo);
        return errorInfo;
    }

    /**
     * 空指针异常
     *
     * @param req  请求信息
     * @param exception 异常信息
     * @return  异常封装
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ErrorInfo nullPointerExceptionHandler(HttpServletRequest req, NullPointerException exception){
        log.error("nullPointerException:", exception);

        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setCode(ResultCode.FAILURE.getCode());
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setUrl(req.getRequestURI());

        log.error("errorInfo:{}", errorInfo);
        return errorInfo;
    }

    /**
     * 运行时异常
     *
     * @param req  请求信息
     * @param exception 异常信息
     * @return  异常封装
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ErrorInfo RuntimeExceptionHandler(HttpServletRequest req, Exception exception){
        log.error("exception:", exception);

        ErrorInfo errorInfo = new ErrorInfo();
        errorInfo.setCode(ResultCode.FAILURE.getCode());
        errorInfo.setMessage(exception.getMessage());
        errorInfo.setUrl(req.getRequestURI());

        log.error("errorInfo:{}", errorInfo);
        return errorInfo;
    }


}
